package com.cellulam.framework.fs.excel.writer;

import com.cellulam.framework.fs.common.DataTable;
import org.apache.commons.io.IOUtils;
import org.jxls.area.Area;
import org.jxls.builder.AreaBuilder;
import org.jxls.builder.xls.XlsCommentAreaBuilder;
import org.jxls.common.CellRef;
import org.jxls.common.Context;
import org.jxls.common.JxlsException;
import org.jxls.transform.Transformer;
import org.jxls.util.TransformerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 *
 */
public class SimpleTableWriter {

    private static final Logger logger = LoggerFactory.getLogger(SimpleTableWriter.class);

    private static final String TABLE_TEMPLATE_NAME = "simple_table_template.xlsx";

    private static byte[] tableTableBytes;

    public static void outputExcel(OutputStream outputStream, DataTable dataTable) {
        InputStream is = new ByteArrayInputStream(getTableTableBytes());
        Transformer transformer = TransformerFactory.createTransformer(is, outputStream);
        AreaBuilder areaBuilder = new XlsCommentAreaBuilder(transformer);
        List<Area> xlsAreaList = areaBuilder.build();
        Area xlsArea = xlsAreaList.get(0);
        Context context = new Context();
        context.putVar("headers", dataTable.getHeaders());
        context.putVar("data", dataTable.getDataRows());
        xlsArea.applyAt(new CellRef("Sheet1!A1"), context);
        try {
            transformer.write();
        } catch (IOException e) {
            logger.error("Failed to write to output stream", e);
            throw new JxlsException("Failed to write to output stream", e);
        }
    }


    private static byte[] getTableTableBytes() {
        if (tableTableBytes != null) {
            return tableTableBytes;
        }

        InputStream is = null;
        try {
            is = SimpleTableWriter.class.getResourceAsStream("/"+TABLE_TEMPLATE_NAME);
            tableTableBytes = IOUtils.toByteArray(is);
        } catch (IOException e) {
            String message = "Failed to readAsList default template file " + TABLE_TEMPLATE_NAME;
            logger.error(message, e);
            throw new JxlsException(message, e);
        } finally {
            IOUtils.closeQuietly(is);
        }
        return tableTableBytes;
    }


}
